import { useState, useEffect } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { 
  getServicesByTab, 
  type OutpatientService,
  type InpatientService,
  type ComprehensiveService
} from '../../api/outpatient'
import './index.css'

function MoreServices() {
  const navigate = useNavigate()
  const [searchParams] = useSearchParams()
  const initialTab = searchParams.get('tab') || 'outpatient'
  
  const [activeTab, setActiveTab] = useState(initialTab)
  const [services, setServices] = useState<(OutpatientService | InpatientService | ComprehensiveService)[]>([])
  const [loading, setLoading] = useState(false)
  const [currentPage, setCurrentPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [searchKeyword, setSearchKeyword] = useState('')
  
  const pageSize = 12 // 每页显示12个项目
  
  const tabConfig = {
    outpatient: { name: '门诊服务', key: 'outpatient' },
    inpatient: { name: '住院服务', key: 'inpatient' },
    comprehensive: { name: '综合服务', key: 'comprehensive' }
  }

  // 加载服务数据
  const loadServices = async (tabType: 'outpatient' | 'inpatient' | 'comprehensive', page: number = 1, keyword: string = '') => {
    setLoading(true)
    try {
      const allData = await getServicesByTab(tabType)
      
      // 搜索过滤
      let filteredData = allData
      if (keyword) {
        filteredData = allData.filter(service => 
          service.name.toLowerCase().includes(keyword.toLowerCase()) ||
          (service.description && service.description.toLowerCase().includes(keyword.toLowerCase()))
        )
      }
      
      // 分页处理
      const startIndex = (page - 1) * pageSize
      const endIndex = startIndex + pageSize
      const pageData = filteredData.slice(startIndex, endIndex)
      
      if (page === 1) {
        setServices(pageData)
      } else {
        setServices(prev => [...prev, ...pageData])
      }
      
      setHasMore(endIndex < filteredData.length)
    } catch (error) {
      console.error('加载服务数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 初始化数据
  useEffect(() => {
    loadServices(activeTab as 'outpatient' | 'inpatient' | 'comprehensive', 1, searchKeyword)
  }, [activeTab])

  // 处理搜索
  const handleSearch = () => {
    setCurrentPage(1)
    loadServices(activeTab as 'outpatient' | 'inpatient' | 'comprehensive', 1, searchKeyword)
  }

  // 加载更多
  const loadMore = () => {
    if (!loading && hasMore) {
      const nextPage = currentPage + 1
      setCurrentPage(nextPage)
      loadServices(activeTab as 'outpatient' | 'inpatient' | 'comprehensive', nextPage, searchKeyword)
    }
  }

  // 处理服务项点击
  const handleServiceClick = (service: OutpatientService | InpatientService | ComprehensiveService) => {
    if (service.route) {
      navigate(service.route)
    } else {
      console.log('点击服务:', service.name)
    }
  }

  // 生成渐变背景色
  const generateGradientColors = (serviceId: number) => {
    const colors = [
      { from: '#e8f3ff', to: '#d4e7ff' },
      { from: '#e9f7ef', to: '#d3f0e0' },
      { from: '#fff2e8', to: '#ffe1cc' },
      { from: '#f2ecff', to: '#e4dbff' },
      { from: '#e8f7ff', to: '#d6eeff' },
      { from: '#fff0f5', to: '#ffd9e6' },
      { from: '#eff8ff', to: '#d9edff' },
      { from: '#f3ffe9', to: '#e2ffd0' }
    ]
    return colors[serviceId % colors.length]
  }

  return (
    <div style={{ minHeight: '100vh', background: '#f5f5f5' }}>
      {/* 顶部导航 */}
      <div style={{ 
        background: '#fff', 
        padding: '12px 16px', 
        borderBottom: '1px solid #eee',
        position: 'sticky',
        top: 0,
        zIndex: 100
      }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <button 
              onClick={() => navigate(-1)}
              style={{ 
                border: 'none', 
                background: 'none', 
                fontSize: 18, 
                marginRight: 12,
                cursor: 'pointer'
              }}
            >
              ←
            </button>
            <h1 style={{ margin: 0, fontSize: 18, fontWeight: 600 }}>
              {tabConfig[activeTab as keyof typeof tabConfig]?.name || '更多服务'}
            </h1>
          </div>
        </div>
        
        {/* 搜索框 */}
        <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
          <input
            type="text"
            placeholder="搜索服务..."
            value={searchKeyword}
            onChange={(e) => setSearchKeyword(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            style={{
              flex: 1,
              padding: '8px 12px',
              border: '1px solid #ddd',
              borderRadius: 8,
              fontSize: 14
            }}
          />
          <button
            onClick={handleSearch}
            style={{
              padding: '8px 16px',
              background: '#1677ff',
              color: '#fff',
              border: 'none',
              borderRadius: 8,
              cursor: 'pointer'
            }}
          >
            搜索
          </button>
        </div>
        
        {/* Tab切换 */}
        <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
          {Object.entries(tabConfig).map(([key, tab]) => (
            <button
              key={key}
              onClick={() => {
                setActiveTab(key)
                setCurrentPage(1)
                setSearchKeyword('')
              }}
              style={{
                padding: '6px 12px',
                background: activeTab === key ? '#1677ff' : '#f5f5f5',
                color: activeTab === key ? '#fff' : '#666',
                border: 'none',
                borderRadius: 6,
                cursor: 'pointer',
                fontSize: 14,
                transition: 'all 0.2s ease'
              }}
            >
              {tab.name}
            </button>
          ))}
        </div>
      </div>

      {/* 服务网格 */}
      <div style={{ padding: '16px' }}>
        <div style={{ 
          display: 'grid', 
          gridTemplateColumns: 'repeat(3, 1fr)', 
          gap: 16,
          marginBottom: 20
        }}>
          {services.map((service) => {
            const colors = generateGradientColors(service.id)
            return (
              <div 
                key={service.id} 
                style={{ 
                  background: '#fff',
                  borderRadius: 12,
                  padding: 16,
                  display: 'flex',
                  flexDirection: 'column',
                  alignItems: 'center',
                  cursor: 'pointer',
                  transition: 'all 0.2s ease',
                  boxShadow: '0 2px 8px rgba(0,0,0,0.06)'
                }}
                onClick={() => handleServiceClick(service)}
                onMouseEnter={(e) => {
                  e.currentTarget.style.transform = 'translateY(-2px)'
                  e.currentTarget.style.boxShadow = '0 4px 16px rgba(0,0,0,0.12)'
                }}
                onMouseLeave={(e) => {
                  e.currentTarget.style.transform = 'translateY(0)'
                  e.currentTarget.style.boxShadow = '0 2px 8px rgba(0,0,0,0.06)'
                }}
              >
                <div style={{
                  width: 48,
                  height: 48,
                  borderRadius: 12,
                  marginBottom: 12,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  background: `linear-gradient(135deg, ${colors.from}, ${colors.to})`,
                  boxShadow: '0 2px 10px rgba(93,110,180,0.08)'
                }}>
                  <span style={{ fontSize: 20 }}>{service.icon}</span>
                </div>
                <div style={{ 
                  fontSize: 14, 
                  fontWeight: 600,
                  textAlign: 'center',
                  lineHeight: 1.2,
                  color: '#333',
                  marginBottom: 4
                }}>
                  {service.name}
                </div>
                {service.description && (
                  <div style={{ 
                    fontSize: 12, 
                    color: '#666',
                    textAlign: 'center',
                    lineHeight: 1.3
                  }}>
                    {service.description}
                  </div>
                )}
              </div>
            )
          })}
        </div>

        {/* 加载更多按钮 */}
        {hasMore && (
          <div style={{ textAlign: 'center', marginBottom: 20 }}>
            <button
              onClick={loadMore}
              disabled={loading}
              style={{
                padding: '12px 24px',
                background: loading ? '#ccc' : '#1677ff',
                color: '#fff',
                border: 'none',
                borderRadius: 8,
                cursor: loading ? 'not-allowed' : 'pointer',
                fontSize: 14
              }}
            >
              {loading ? '加载中...' : '加载更多'}
            </button>
          </div>
        )}

        {/* 没有更多数据提示 */}
        {!hasMore && services.length > 0 && (
          <div style={{ 
            textAlign: 'center', 
            color: '#999', 
            fontSize: 14,
            marginBottom: 20
          }}>
            没有更多数据了
          </div>
        )}

        {/* 空状态 */}
        {!loading && services.length === 0 && (
          <div style={{ 
            textAlign: 'center', 
            padding: '40px 20px',
            color: '#999'
          }}>
            <div style={{ fontSize: 48, marginBottom: 16 }}>🔍</div>
            <div style={{ fontSize: 16, marginBottom: 8 }}>暂无相关服务</div>
            <div style={{ fontSize: 14 }}>试试其他关键词搜索</div>
          </div>
        )}
      </div>
    </div>
  )
}

export default MoreServices
